import React, { Component } from 'react';
import { Row, Col, Card, Form, Input, Button, Table, Modal, Select, Divider } from 'antd';
import { connect } from 'dva';
import styles from './List.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import AddBusiness from './AddBusiness';
import ShowBusinessInfo from './ShowBusinessInfo';
import globalConstant from '../../utils/globalConstant';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ bussiness, general, loading }) => ({
  bussiness,
  general,
  loading: loading.models.bussiness,
}))
@Form.create()
export default class BusinessManagement extends Component {
  state = {
    showBusinessAddVisible: false,
    showBusinessInfoVisible: false,
    id: undefined,
    districtId: undefined,
    pageNum: globalConstant.paging.defaultPageNum,
    pageSize: globalConstant.paging.defaultPageSize,
    form: {},
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'bussiness/fetch',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
    dispatch({
      type: 'general/getDistrictList',
    });
  }
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
    console.log(params);
    dispatch({
      type: 'bussiness/fetch',
      payload: params,
    });
  }
  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      console.log(fieldsValue);
      dispatch({
        type: 'bussiness/fetch',
        payload: {
          communityId: fieldsValue.communityId === -1 ? null : fieldsValue.communityId,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          keywordsValue: fieldsValue.keywordsValue || null,
        },
      });
      this.setState({
        form: {
          communityId: fieldsValue.communityId === -1 ? null : fieldsValue.communityId,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          keywordsValue: fieldsValue.keywordsValue || null,
        },
      });
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      form:{},
    });
    dispatch({
      type: 'bussiness/fetch',
      payload: {
        pageNum: globalConstant.paging.pageNum,
        pageSize: globalConstant.paging.pageSize,
      },
    });
  }
  handleSelectDistrict = (districtId) => {
    this.setState({
      districtId,
    });
  };
  handleCommunityFocus = () => {
    this.props.form.setFieldsValue({ community: -1 });
    this.props.dispatch({
      type: 'general/getCommunityListByDistrict',
      payload: {
        districtId: this.state.districtId,
      },
    });
  }
  handleAddBusinessModal= () => {
    this.setState({
      showBusinessAddVisible: true,
    });
  }
  handleAddBusinessModalCancel =(refreshFlag) => {
    this.setState({
      showBusinessAddVisible: false,
    });
    if (refreshFlag) {
      this.props.dispatch({
        type: 'bussiness/fetch',
        payload: {
          pageNum: this.state.pageNum,
          pageSize: this.state.pageSize,
          ...this.state.form,
        },
      });
    }
  }
  handleInfoBusinessModal= (value) => {
    this.setState({
      showBusinessInfoVisible: true,
      id: value.id,
    });
  }
  handleInfoBusinessModalCancel =() => {
    this.setState({
      showBusinessInfoVisible: false,
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const districtArray = [{ id: -1, value: '全部' }];
    const communityArray = [{ id: -1, value: '全部' }];
    this.props.general.districtList.map((item) => {
      return (
        districtArray.push({ id: item.id, value: item.districtName })
      );
    });
    this.props.general.communityList.map((item) => {
      return (
        communityArray.push({ id: item.id, value: item.communityName })
      );
    });
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 24 }}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input placeholder="请输入搜索关键字" />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="区域">
              {getFieldDecorator('districtId')(
                <Select placeholder="请选择" onChange={(value) => { this.handleSelectDistrict(value); }}>
                  {
                    districtArray.map((item, index) => {
                      return (
                        <Option
                          key={index.toString()}
                          value={item.id}
                        >
                          {item.value}
                        </Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="小区">
              {getFieldDecorator('communityId')(
                <Select placeholder="请选择" onFocus={() => { this.handleCommunityFocus(); }}>
                  {
                    communityArray.map((item, index) => {
                      return (
                        <Option
                          key={index.toString()}
                          value={item.id}
                        >
                          {
                            item.value
                          }
                        </Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            <span className={styles.submitButtons}>
              <Button icon="search" type="primary" htmlType="submit" >查询</Button>
              <Button icon="reload" style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    console.log(this.props.general);
    const { bussiness: { bussinessList }, loading } = this.props;
    const { showBusinessAddVisible, showBusinessInfoVisible, id } = this.state;
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
      },
      {
        title: '运营商',
        dataIndex: 'bussinessName',
      },
      {
        title: '下行网速',
        dataIndex: 'netSpeeds',
        render: (text, record, index) => {
          const networkSpeedArray = [];
          text.map(item => (networkSpeedArray.push(`${item.networkSpeed}M`)));
          return networkSpeedArray.toString();
        },
      },
      {
        title: '城市',
        dataIndex: 'bussinessCityName',
      },
      {
        title: '操作',
        key: 'key',
        render: (text, record, index) => {
          return (
            <div key={index.toString()}>
              <Button type="primary" onClick={() => { this.handleInfoBusinessModal(text); }} >
                查看详情
              </Button>
            </div>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: bussinessList && bussinessList.totals,
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
      ...globalConstant.pagingFormat,
    };
    return (
      <PageHeaderLayout title="业务管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            <Divider />
            <Card bordered>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handleAddBusinessModal()}>
                  添加
                </Button>
              </div>
              <Table
                bordered
                rowKey={record => record.id}
                loading={loading}
                dataSource={bussinessList && bussinessList.items}
                columns={columns}
                pagination={paginationProps}
                onChange={this.handleStandardTableChange}
              />
            </Card>
          </div>
        </Card>
        <Modal
          visible={showBusinessAddVisible}
          title="添加业务"
          footer={null}
          width="60%"
          onCancel={() => this.handleAddBusinessModalCancel()}
          destroyOnClose
        >
          <AddBusiness handleAddModal={this.handleAddBusinessModalCancel.bind(this)} />
        </Modal>
        <Modal
          visible={showBusinessInfoVisible}
          title="业务详情"
          footer={null}
          width="60%"
          onCancel={() => this.handleInfoBusinessModalCancel()}
          destroyOnClose
        >
          <ShowBusinessInfo data={id} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
